package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"zhaowei/models/cache"
	"zhaowei/pkg"

	"zhaowei/baidurpc/baidurpc"
	"zhaowei/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *baidurpc.SendSmsRequest) (*baidurpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	get, _ := cache.Rdb.Get(cache.Ctx, "sendsms"+in.Mobile).Int()
	if get >= 1 {
		return nil, fmt.Errorf("一分钟内已发送一次,请过会再试")
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, fmt.Errorf("发送失败")
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}
	cache.Rdb.Set(cache.Ctx, "sendsms"+in.Mobile, code, 0)
	inc, _ := cache.Rdb.Incr(cache.Ctx, "sendsms"+in.Mobile).Result()
	if inc == 1 {
		cache.Rdb.Expire(cache.Ctx, "sendsms"+in.Mobile, time.Minute*1)
	}
	return &baidurpc.SendSmsResponse{}, nil
}
